import CrudService from '../global/CrudService'

let instance = null

// 后端路径
const prefix = '/rptTask'

const transformItem = (model) => {
  const { colList } = model
  return {
    ...model,
    col_name: colList.map(e => e.col_name).join(';'),
    col_type: colList.map(e => e.col_type).join(';'),
  }
}

class Service extends CrudService {
  constructor() {
    super(prefix)
    this.deletePath = `${prefix}/deleteItem_sz`
    return instance || this
  }

  static getInstance() {
    if (!instance) {
      instance = new Service()
    }
    return instance
  }

  /**
   * 获取列表
   * @param model
   * @returns {Promise<*>}
   */
  getList = async (model) => {
    const payload = await this.get(`${prefix}/queryItemList_sz_pagi`, model) || {}
    const { list = [] } = payload
    list.forEach(e => {
      const { col_type = '', col_name = '' } = e
      if (col_name) {
        const types = col_type.split(',')
        e.colList = col_name.split(',').map((e, i) => ({ col_name: e, col_type: types[i] }))
      } else {
        e.colList = []
      }
    })
    // console.log(payload)
    return payload
  }

  /**
   * 新增
   * @param model
   * @returns {Promise<*>}
   */
  addItem = async (model) => {
    return this.post(`${prefix}/insertItem_sz`, transformItem(model))
  }

  /**
   * 编辑
   * @param model object
   * @returns {Promise<*>}
   */
  editItem = async (model) => {
    return this.post(`${prefix}/updateItem_sz`, transformItem(model))
  }

  /**
   * 全量不分页
   * @param model
   * @returns {Promise<*>}
   */
  getAllList = async (model) => {
    return this.get(`${prefix}/queryItemList_sz`, model)
  }
}

export default Service.getInstance()
